<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <!-- <script src="https://unpkg.com/vue@next"></script> -->
    <script src="https://www.unpkg.com/vue@3.2.47/dist/vue.global.js" type="text/javascript" charset="utf-8"></script>
 
    <script src="https://www.unpkg.com/axios@1.3.4/dist/axios.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="https://www.unpkg.com/spark-md5@3.0.2/spark-md5.js" type="text/javascript" charset="utf-8"></script>

</head>
<body>
    <div id="app">
        {{ counter }}
        <input type="file" hidden="hidden" id="myfile" />
        <button @click="onTest"> 上传文件</button>
    </div>

    <script>

        const App = {
            data() {
                return {
                    counter: 100
                }
            }, methods: {
                onTest: async function () {

                    var res = await this.onUpload()
                    const instance = axios.create({
                        baseURL: 'http://localhost:805/',
                        timeout: 360000,
                        headers: { 'X-Custom-Header': 'foobar' }
                    });
                    for (var x of res) {
                        var forms = new FormData()

                        forms.append('start', x.start)
                        forms.append('hash', x.hash)
                        forms.append('end', x.end)
                        forms.append('chunkHash', x.chunkHash)
                        forms.append('file', x.file)
                     
                        var uploadChunkFileResult=   await instance.post(
                            '/File/BigUploadFile',
                            forms
                        )
                       
                        if (uploadChunkFileResult.status !== 200) throw new Exception('上传失败')
                    }


                    var mergeResult = await instance.post(
                        '/File/mergeBigUploadFile?hash=' + res[0].hash + "&filecount=" + res.length
                    )

                    if (mergeResult.data.Tag === 1) {
                        console.log('uploadresult', mergeResult.data)
                    } else {
                        throw new Exception('文件合并失败')
                    }



                    //   console.log("res", instance);

                },
                onGetMd5: function (file) {
                    return new Promise((resolve, reject) => {



                        var chunkSize = 10 * 1024 * 1024;                            // Read in chunks of 2MB
                        var chunks = Math.ceil(file.size / chunkSize);
                        var currentChunk = 0;
                        var spark = new SparkMD5.ArrayBuffer();
                        var fileReader = new FileReader();

                        fileReader.onload = function (e) {

                            spark.append(e.target.result);                   // Append array buffer
                            currentChunk++;

                            if (currentChunk < chunks) {
                                loadNext();
                            } else {

                                resolve(spark.end())
                            }
                        };

                        fileReader.onerror = function (e) {
                            reject(' something went wrong.', e);
                        };

                        function loadNext() {
                            var start = currentChunk * chunkSize,
                                end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

                            fileReader.readAsArrayBuffer(file.slice(start, end));
                        }

                        loadNext();
                    });
                },
                onGetfileChunkList:async function (_file, md5) {
                    const size = 10 * 1024 * 1024;


                    const fileChunkList = [];


                    var matchfilename = /([^\\/]+)\.([^\\/]+)/i.exec(_file.name);

                    var suffix = matchfilename[2];

                    let cur = 0;
                    let count = 0;
                    while (cur < _file.size) {
                        var end = cur + size;
                        if (end > _file.size) end = _file.size
                        var blob = _file.slice(cur, end);
                        var chunkfilename = matchfilename[1] + ".[" + count + "_" + cur + "]." + suffix;    //    拼装新的文件名，后台通过中间后缀名来定位合并
                 
                        var chunkfile = new File([blob], chunkfilename, { type: _file.type, lastModified: Date.now() });
                        fileChunkList.push({ file: chunkfile, start: cur, end: end, index: count, hash: md5, chunkHash:await this.onGetMd5(chunkfile) });
                        cur += size;
                        count++;
                    }

                    return fileChunkList;
                },
                onUpload: function () {
                    return new Promise(resolve => {


                        var selectedFile = document.getElementById("myfile");
                        selectedFile.onchange = async (x) => {
                            var file = selectedFile.files[0];
                            console.log("计算文件md5值");
                            var md5 = await this.onGetMd5(file);
                            console.log("文件进行切片");
                            var fileChunkList = await this.onGetfileChunkList(file, md5);
                                resolve(fileChunkList);

                           



                        }

                        selectedFile.click();
                    });

                }
            }
        };
        Vue.createApp(App).mount('#app');
    </script>
</body>
</html>
